package com.netty.chapter07_messagepack;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import org.msgpack.MessagePack;

import java.util.List;

/**
 * Package Name:com.netty.chapter07_messagepack
 * Description: 自定义解码器
 * Date:2016/9/3 14:22
 * Copyright (c) 2016, zhongmu@suneee.com All Rights Reserved.
 */
public class Netty03_msg_pack_self_decoder extends MessageToMessageDecoder<ByteBuf> {
    /**
     * 先取缓冲区字节流（及长度），然后使用messagePack.read读取解码
     * @param arg0
     * @param arg1
     * @param arg2
     * @throws Exception
     */
    @Override
    protected void decode(ChannelHandlerContext arg0, ByteBuf arg1, List<Object> arg2) throws Exception {

        final  byte[] array ;
        //读取序列化后的byteBuf缓冲区中字节流的长度
        final int length = arg1.readableBytes();
        array = new byte[length];
        arg1.getBytes(arg1.readerIndex(),array,0,length);
        MessagePack messagePack = new MessagePack();
        arg2.add(messagePack.read(array));
    }
}
